$.jgrid.defaults.responsive = true;
$.jgrid.defaults.styleUI = 'Bootstrap';

$(document).ready(function () {
    var $jqGrid = $("#jqGrid");
    RFQ.jqGrid("#jqGrid").init({
        url: ctx+'/rfqRequest/rfqRequestListP',
        colModel: [
            {
                label: '序号',
                name: 'id',
                index: 'id',
                width: 80,
                key: true,
                hidden:true
            },
            {
                label: '未审核供应商数量',
                name: 'checkNum',
                index: 'checkNum',
                hidden:true
            },
            {
                label: '类型',
                name: 'rfqMethod',
                index: 'a.RFQ_METHOD',
                width: 50,
                align:'center',
                formatter:rfqMethodFormatter
            },
            {
                label: '询价单号',
                name: 'unifiedRfqNum',
                index: 'a.UNIFIED_RFQ_NUM',
                align:'center',
                hidden:true,
                width: 80,
                formatter:selectFormatter
            },
            {
                label: '询价单号',
                name: 'ouRfqNum',
                index: 'a.OU_RFQ_NUM',
                align:'center',
                width: 80,
                formatter:selectFormatter
            },
            {
                label: '询单标题',
                name: 'title',
                index: 'a.TITLE',
                align:'center',
                width: 80
            },
            {
                label: '创建人',
                name: 'recCreatorUsername',
                index: 'a.REC_CREATOR_USERNAME',
                align:'center',
                width: 60
            },
            {
                label: '创建时间',
                name: 'recCreateTime',
                index: 'a.REC_CREATE_TIME',
                align:'center',
                width: 80
            },
            {
                label: '报名截止时间',
                name: 'registrationEndDate',
                index: 'b.REGISTRATION_END_DATE',
                align:'center',
                width: 80
            },
            {
                label: '报价起止时间',
                name: 'startDate',
                index: 'a.START_DATE',
                align:'center',
                width: 90,
                formatter:startEndTimeFormatter
            },
            {
                label: '询单状态',
                name: 'type',
                index: 'a.TYPE',
                align:'center',
                width: 80,
                formatter: formatRfqRequestType
            },

            {
                width: 80,
                label: '操作',
                name: 'id',
                index: 'id',
                sortable:false,
                formatter: actFormatter
            }
        ],
        rowNum: 20,//每页显示记录数
        rowList: [20,30, 50, 100],//用于改变显示行数的下拉列表框的元素数组。
        sortname: 'a.REC_CREATE_TIME',
        sortorder: 'desc',
        pager: "#jqGridPager"
    });

    function formatTitle(cellValue, options, rowObject) {
        return cellValue.substring(0, 50) + "...";
    };

    function actFormatter(cellvalue, options, rawObject) {
        var rtype = rawObject.type;
        var detailBtn = '<span class="ml5"><a class="btn btn-sm btn-info re js-check" data-id="'+rawObject.id+'" data-type="'+rawObject.type+'"  data-action="rfqRequestDetail(\'' + rawObject.id + '\')" href="javascript:;"><i class="icon icon-zoom-in"></i> 查看</a></span>';
        if(rtype == '0'){//草稿
            detailBtn =  '<span class="ml5"><a class="btn btn-sm btn-success js-check" data-id="'+rawObject.id+'" data-type="'+rawObject.type+'"  data-action="editRfqRequest(\'' + rawObject.id +'\''+'\,' +'\''+rawObject.rfqMethod+ '\')"  href="javascript:;"><i class="icon icon-edit-sign"></i> 编辑</a></span>';
        }else if(rtype == '1'){//创建待审批
            detailBtn;
        }else if(rtype == '2'){//待发布
            detailBtn =  '<span class="ml5"><a class="btn btn-sm btn-warning js-check" data-id="'+rawObject.id+'" data-type="'+rawObject.type+'"  data-action="rfqRequestRelease(\'' + rawObject.id + '\')" href="javascript:;"><i class="icon icon-rocket"></i> 发布</a></span>';
        }else if(rtype == '5'){//报名中
            if(rawObject.checkNum=="0"){
                detailBtn =  '<span class="ml5">' +
                    '<a class="btn btn-sm btn-warning js-check" data-id="'+rawObject.id+'" data-type="'+rawObject.type+'" ' +
                    'data-action="rfqRequestState(\'' + rawObject.id + '\')" href="javascript:;">' +
                    '<i class="icon icon-check-sign"></i> 审批</a></span>';
            }else{
                detailBtn =  '<span class="ml5">' +
                    '<a class="btn btn-sm btn-warning js-check re" data-id="'+rawObject.id+'" data-type="'+rawObject.type+'" ' +
                    'data-action="rfqRequestState(\'' + rawObject.id + '\')" href="javascript:;">' +
                    '<i class="icon icon-check-sign"></i> 审批<span class="rtNum">'+rawObject.checkNum+'</span></a></span>';
            }
        }else if(rtype == '6'){//报价中
            detailBtn =  '<span class="ml5"><a class="btn btn-sm btn-info js-check" data-id="'+rawObject.id+'" data-type="'+rawObject.type+'"  data-action="baoJiaState(\'' + rawObject.id + '\')" href="javascript:;"><i class="icon icon-check-sign"></i> 审核</a></span>';
        }else if(rtype == '3'){//待报价
            detailBtn =  '<span class="ml5"><a class="btn btn-sm btn-info js-check" data-id="'+rawObject.id+'" data-type="'+rawObject.type+'"  data-action="baoJiaState(\'' + rawObject.id + '\')" href="javascript:;"><i class="icon icon-zoom-in"></i> 查看</a></span>';
        }else if(rtype == '7'){//待开标
            detailBtn =  '<span class="ml5"><a class="btn btn-sm btn-danger js-check" data-id="'+rawObject.id+'" data-type="'+rawObject.type+'"  data-action="kaiBiaoState(\'' + rawObject.id +'\''+'\,' +'\''+rawObject.rfqMethod+ '\')" href="javascript:;"><i class="icon icon-folder-open-alt"></i> 开标</a></span>';
        }else if(rtype == '8'&& 'RAQ'==rawObject.rfqMethod){//待核价
            detailBtn =  '<span class="ml5"><a class="btn btn-sm btn-success js-check" data-id="'+rawObject.id+'" data-type="'+rawObject.type+'"  data-action="designateResultState(\'' + rawObject.unifiedRfqNum + '\')" href="javascript:;"><i class="icon icon-yen icon-w13"></i> 核价</a></span>';
        }else if(rtype == '8'&& 'DAC'==rawObject.rfqMethod){//待授标
            detailBtn =  '<span class="ml5"><a class="btn btn-sm btn-success js-check" data-id="'+rawObject.id+'" data-type="'+rawObject.type+'"  data-action="designateContract(\'' + rawObject.unifiedRfqNum + '\')" href="javascript:;"><i class="icon icon-yen icon-w13"></i> 授标</a></span>';
        }
        //else if(rtype == '9'){//结果待审批
        //	detailBtn;
        //}
        else if(rtype == '10' || rtype == '9'){//已结束
            detailBtn =  '<span class="ml5"><a class="btn btn-sm btn-info js-check" data-id="'+rawObject.id+'" data-type="'+rawObject.type+'"  data-action="rfqRequestEnd(\'' + rawObject.id+'\''+'\,' +'\''+ rawObject.unifiedRfqNum +'\''+'\,' +'\''+rawObject.rfqMethod+ '\')" href="javascript:;"><i class="icon icon-zoom-in"></i> 查看</a></span>';
        }else if(rtype == '11'){//已作废
            detailBtn =  '<span class="ml5"><a class="btn btn-sm btn-info js-check" data-id="'+rawObject.id+'" data-type="'+rawObject.type+'"  data-action="rfqRequestState(\'' + rawObject.id + '\')" href="javascript:;"><i class="icon icon-zoom-in"></i> 查看</a></span>';
        }else if(rtype == '12'){//已流标
            detailBtn =  '<span class="ml5"><a class="btn btn-sm btn-info js-check" data-id="'+rawObject.id+'" data-type="'+rawObject.type+'"  data-action="rfqRequestState(\'' + rawObject.id + '\')" href="javascript:;"><i class="icon icon-zoom-in"></i> 查看</a></span>';
        }else if(rtype == '13'){//结果待发布
            detailBtn =  '<span class="ml5"><a class="btn btn-sm btn-warning js-check" data-id="'+rawObject.id+'" data-type="'+rawObject.type+'"  data-action="pendingRelease(\'' + rawObject.id +'\''+'\,' +'\''+rawObject.unifiedRfqNum +'\''+'\,' +'\''+rawObject.rfqMethod+ '\')"  href="javascript:;"><i class="icon icon-rocket"></i> 发布</a></span>'
        }else if(rtype == '14'){//多伦报价创建待审批
            detailBtn =  '<span class="ml5"><a class="btn btn-sm btn-info js-check" data-id="'+rawObject.id+'" data-type="'+rawObject.type+'"  data-action="launchedSeveralAuditing(\'' + rawObject.id + '\')"  href="javascript:;"><i class="icon icon-zoom-in"></i> 查看</a></span>'
        }else if(rtype == '15'){//多伦报价待发布
            detailBtn =  '<span class="ml5"><a class="btn btn-sm btn-warning js-check" data-id="'+rawObject.id+'" data-type="'+rawObject.type+'"  data-action="launchedSeveralRelease(\'' + rawObject.id + '\')"  href="javascript:;"><i class="icon icon-rocket"></i> 发布</a></span>'
        }
        //TODO 缺少公布按钮
        return detailBtn;
    };


    //状态校验
    $jqGrid.on('click','.js-check', function () {
        var $this = $(this);
        var id = $this.data('id');
        var type = $this.data('type');
        var action =  $this.data('action');
        RFQ.post(ctx+'/rfqRequest/checkState',{id:id,type:type}, function (msg) {
            eval(action);
        });
    });


    var $myTab = $('#myTab');
    //搜索按钮点击
    $('button.btnSearch').on('click',function(){
        jqGridReload();
    });

    //标签页切换
    $myTab.find('[data-toggle]').on('shown.zui.tab', function(e) {
        var $activeTab = $(e.target);
        //表单重置
        var $activeContent = $($activeTab.attr('href'));
        $activeContent.find('.searchFormTab')[0].reset();
        //状态重置
        var $lis = $activeContent.find('.navbar-nav li');
        $lis.removeClass('active');
        //默认为全部状态激活
        $lis.eq(0).addClass('active');
        //数据重新加载
        jqGridReload();
        var rfqMethod = $activeTab.data('method')||'';
        //TODO 数据统计
        $.get('fingByRfqTypeP',{rfqMethod:rfqMethod},function(data){
            var staticDatas = {};
            $.each(data,function(i,d){
                staticDatas[d.type] = d.count;
            });
            $lis.each(function(){
                var $a = $(this).find('a');
                var type = $a.data('type');
                var $stext = $a.find('strong');
                if(type == '101'){
                    $stext.text('('+((staticDatas['2']||0)+(staticDatas['15']||0))+')');
                }else if( type == '102'){
                    $stext.text('('+((staticDatas['1']||0)+(staticDatas['14']||0))+')');
                }else{
                    $stext.text('('+(staticDatas[type]||0)+')');
                }
            });
        },'json');
    });

    //状态页切换
    $('div.tab-content').on('click','.navbar-nav a',function(){
        var $this = $(this);
        $this.parent().addClass('active').siblings().removeClass('active');
        jqGridReload();
    });

    function jqGridReload(params){
        var chooseName;
        //选择的模式
        var $activeTab = $myTab.find('.active a');
        var rfqMethod = $activeTab.data('method')||'';

        /** 采购组织下拉搜索框代码  start **/
        if (rfqMethod == ''){//选择了全部类型
           chooseName=$("#ouName1").val();
           if (chooseName != null && chooseName != "") {
               for (var i = 0; i < chinese_fullname.length; i++) {
                   if (chooseName == chinese_fullname[i]) {
                      $("#uuCode1").val(bsp_company_code[i]);
                      break;
                   }else {
                       $("#uuCode1").val('');
                   }
               }
           } else {
               $("#uuCode1").val('');
           }
       }else if (rfqMethod == "RAQ"){//选择了询比价
           chooseName=$("#ouName3").val();
            if (chooseName != null && chooseName != "") {
                for (var i = 0; i < chinese_fullname.length; i++) {
                    if (chooseName == chinese_fullname[i]) {
                        $("#uuCode3").val(bsp_company_code[i]);
                        break;
                    }else {
                        $("#uuCode3").val('');
                    }
                }
            } else {
                $("#uuCode3").val('');
            }
       }else{//选择了其他,反向竞价之类的...
       }
        /** 采购组织下拉搜索框代码  end **/

        //选择的状态以及表单
        var $activeContent = $($activeTab.attr('href'));
        var type = $activeContent.find('.navbar-nav .active a').attr('data-type')||'';
        //表单id
        var formId= $activeContent.find('.searchFormTab')[0].id;
        var params = {rfqMethod:rfqMethod,type:type};
        var postData = $.extend(form2Json(formId),params);
        $jqGrid.jqGrid('setGridParam', {
            postData: postData,
            page: 1
        }).trigger("reloadGrid");
    }

});

function rfqRequestRelease(id){
    location.href = ctx+"/rfqRequest/rfqRequestRelease?id=" + id;
}
function rfqRequestDetail(id) {
    location.href = ctx+"/rfqRequest/rfqRequestDetail?id=" + id;
}

function editRfqRequest(id,rfqMethod) {
    if('RAQ'==rfqMethod){
        location.href = ctx+"/rfqRequest/toUpdateRfqRequest?id=" + id;
    }else if('DAC'==rfqMethod){
        location.href = ctx+"/dacReverseAuction/toUpdateDacReverseAuction?id=" + id;
    }

}

function deleteRfqRequest(id) {
    location.href = ctx+"/rfqRequest/delRfqRequest?id=" + id;
}

function rfqRequestState(id){
    location.href = ctx + "/rfqRequestState/init?id=" + id;
}

function designateResultState(unifiedRfqNum){
    location.href =ctx + "/designateResult/init?unifiedRfqNum=" + unifiedRfqNum;
}

function baoJiaState(id){
    location.href =ctx + "/rfqRequestState/init?id=" + id;
}

function designateContract(unifiedRfqNum){
    location.href =ctx + "/designateContract/init?unifiedRfqNum=" + unifiedRfqNum;
}

function kaiBiaoState(id,rfqMethod){
    if('RAQ'==rfqMethod){
        location.href =ctx + "/rfqRequestState/init?id=" + id;
    }else if('DAC'==rfqMethod){
        location.href =ctx + "/designateContract/tenders?id=" + id;
    }

}
function launchedSeveralAuditing(id) {
    location.href = ctx+"/rfqLaunchedSeveralPrice/launchedServeralAuditDetail?id="+id;
}
function launchedSeveralRelease(id) {
    location.href = ctx+"/rfqLaunchedSeveralPrice/launchedServeralReleaseinit?id="+id;
}
/**
 * 起止时间格式化
 */
function startEndTimeFormatter(cellvalue, options, rawObject) {
    var endDate = rawObject.quotationEndDate||'';
    return (cellvalue||'') +'~\n'+ endDate;
}

/**
 * 类型格式化
 */
function rfqMethodFormatter(cellvalue, options, rawObject) {
    var result = '';
    if('RAQ'==cellvalue){
        result = '<span class="label label-warning">询价</span>';
    }else if('RFQ'==cellvalue){
        result = '<span class="label label-primary">招标</span>';
    }else if('DAC'==cellvalue){
        result = '<span class="label label-warning">竞价</span>';
    }else{
        result = '<span class="label label-danger">未知</span>';
    }
    return result;
}

/**
 * 询单编号链接跳转
 */
function selectFormatter(cellvalue, options, rawObject) {
    var id = rawObject.id;
    if('RAQ'==rawObject.rfqMethod){
        return "<a class='blue' href='"+ctx+"/rfqRequest/rfqRequestDetail?id="+id+"' target='_blank'>"+cellvalue+"</a>";
    }else if('DAC'==rawObject.rfqMethod){
        return "<a class='blue' href='"+ctx+"/dacReverseAuction/reverseAuctionDetail?id="+id+"' target='_blank'>"+cellvalue+"</a>";
    }

}

function pendingRelease(id,unifiedRfqNum,rfqMethod){
    if('RAQ'==rfqMethod){
        location.href =ctx+"/rfqRequest/pendingRelease?id=" + id;
    }else if('DAC'==rfqMethod){
        location.href =ctx + "/designateContract/init?unifiedRfqNum=" + unifiedRfqNum;
    }
}
function rfqRequestEnd(id,unifiedRfqNum,rfqMethod){
    if('RAQ'==rfqMethod){
        location.href =ctx+"/rfqQuotationNotice/init?requestId=" + id;
    }else if('DAC'==rfqMethod){
        location.href =ctx + "/designateContract/init?unifiedRfqNum=" + unifiedRfqNum;
    }

}